package com.JZ.QM.exception;

import com.JZ.QM.common.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lyp
 * @email lyp@gmail.com
 * @date 2020/6/16 22:27
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.JZ.QM.controller")
public class ExceptionControllerAdvice {

    /**
     * 数据校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handleVaildException(MethodArgumentNotValidException e){
        //绑定结果
        BindingResult bindingResult = e.getBindingResult();
        //定义错误映射
        Map<String,String> errorMap = new HashMap<>();

        log.error("出现问题{},异常类型{}",e.getMessage(),e.getClass());
        bindingResult.getFieldErrors().forEach((fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        }));

        return CommonResult.error(400,"数据校验出现问题").put("data",errorMap);
    }


    /**
     * 默认全局异常处理
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

          log.error("出现问题{},异常类型{}",e.getMessage(),e.getClass());

          return CommonResult.error();
    }

}
